<script lang="ts" setup>
import { nextTick, reactive, ref } from 'vue'
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import TnInput from '@tuniao/tnui-vue3-uniapp/components/input/src/input.vue'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
import TnEmpty from '@tuniao/tnui-vue3-uniapp/components/empty/src/empty.vue'
import TnPopup from '@tuniao/tnui-vue3-uniapp/components/popup/src/popup.vue'
import TnSearchBox from '@tuniao/tnui-vue3-uniapp/components/search-box/src/search-box.vue'
import TnCommentList from 'tnuiv3p-tn-comment-list/index.vue'
import TnDateTimePicker from '@tuniao/tnui-vue3-uniapp/components/date-time-picker/src/date-time-picker.vue'
import TnScrollList from '@tuniao/tnui-vue3-uniapp/components/scroll-list/src/scroll-list.vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import type { NavbarRectInfo } from '@tuniao/tnui-vue3-uniapp'
import type {
  TnCommentListInstance,
  TnReplyCommentParams,
  TnShowMoreCommentParams,
} from 'tnuiv3p-tn-comment-list'
import PageContainer from '@/components/page-container/index'
import circles from '@/api/circles.js'
import circlesPost from '@/api/circlesPost.js'
import user from '@/api/user.js'
import { CHANNEL, FILE_URL, USER_INFO, USER_TOKEN } from '@/api/config'

const paging = ref(null)
const commentListRef = ref<TnCommentListInstance>()
// 导航栏初始化完毕
const navbarInitFinishHandle = (info: NavbarRectInfo) => {
  navbarHeight.value = info.height
}
// 导航栏的高度
const navbarHeight = ref(0)

// 表单数据
const state = reactive({
  loading: false,
  circlesPostId: 0,
  userToken: '',
  userInfo: {
    id: 0,
    avatar: '',
    nickname: '',
  },
  commentPopup: false,
  commentListPopup: false,
  commentList: [],
  contentPopup: false,
  content: '',
  updateDate: '',
  cardCur: 0,
  videoLists: [],
  replyContent: '',
  textareaFocus: false,
  replyNickname: '',
  replyCommentId: 0,
  operatePopup: false,
  stickyPeriodDate: '',
  mpUrlLink: '',
  currentCirclesPost: {
    id: 0,
    circles_id: 0,
    user_id: 0,
    user: {
      id: 0,
      avatar: '',
      nickname: '',
    },
    user_is_like: 0,
    like_total: 0,
    comment_total: 0,
    like_users_num: 0,
    circles_manage: 0,
    attachment: [],
    attachment_type: '',
  },
  showStickyPeriodPopup: false,
  openDateTimePicker: false,
})

const queryList = (pageNo: any, pageSize: any) => {
  circlesPost
    .videoLists({
      page: pageNo,
      page_size: pageSize,
      circles_post_id: state.circlesPostId,
    })
    .then((res) => {
      state.currentCirclesPost = res.data[0]
      paging.value.complete(res.data)
    })
    .catch((err) => {
      paging.value.complete(false)
    })
}

const getCirclesPostDetailComments = () => {
  circlesPost
    .circlesPostDetailComments({
      circles_post_id: state.circlesPostId,
    })
    .then((res) => {
      if (res.code == 1) {
        state.commentList = res.data
      }
    })
    .catch((err) => {
      console.log(err, 'getCirclesPostDetailComments')
    })
}

const cardSwiper = (e: { detail: { current: number } }) => {
  state.cardCur = e.detail.current
  for (let i = 0; i < state.videoLists.length; i++) {
    const videoContext = uni.createVideoContext(
      `video-${state.videoLists[state.cardCur]['id']}`,
      this
    )
    if (i === state.cardCur) {
      // #ifdef H5
      videoContext.play()
      // #endif
      // #ifndef H5
      videoContext.play()
      // #endif
    } else {
      // #ifdef MP-WEIXIN
      videoContext.stop()
      // #endif
      // #ifndef MP-WEIXIN
      videoContext.pause()
      // #endif
    }
  }
  state.circlesPostId = state.videoLists[state.cardCur]['id']
  state.currentCirclesPost = state.videoLists[state.cardCur]
  getCirclesPostDetailComments()
}
const showCommentPopup = (id: number) => {
  state.circlesPostId = id
  state.commentListPopup = true
}
const closeCommentPopup = () => {
  state.commentPopup = false
  state.textareaFocus = false
}

const clickCommentInput = () => {
  console.log(state.currentCirclesPost, 'currentCirclesPost')
  state.commentPopup = true
  nextTick(() => {
    state.textareaFocus = true
  })
  state.replyContent = ''
  state.replyNickname = state.currentCirclesPost.user.nickname
  state.replyCommentId = 0
}
const showOperatePopup = (item) => {
  state.operatePopup = true
  state.currentCirclesPost = item
  state.circlesPostId = item.id
}
const clickContent = (content: string, updateDate: string) => {
  state.contentPopup = true
  state.content = content
  state.updateDate = updateDate
}
const navUserHomePage = (uId: number) => {
  tnNavPage(`/pagesA/userhome?otherUserId=${uId}`)
}
const shareWechat = () => {
  state.operatePopup = false
}
// 生成微信小程序链接
const generateMpUrlLink = () => {
  circlesPost
    .generateMpUrlLink({
      path: '/circlesPostPages/detail',
      query: `?circlesPostId=${state.circlesPostId}`,
    })
    .then((res) => {
      console.log(res, 'generateMpUrlLink')
      if (res.code == 1) {
        state.mpUrlLink = res.data
        uni.setClipboardData({
          data: res.data,
          success: () => {
            uni.showToast({
              title: '复制成功',
            })
          },
          fail: (error) => {
            console.log('失败', error)
            uni.showToast({
              title: '复制失败',
              icon: 'none',
            })
          },
        })
        state.operatePopup = false
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        })
      }
    })
    .catch((err) => {
      console.log(err, 'generateMpUrlLink')
    })
}
const jumpCirclesPostReport = () => {
  if (state.userToken == '') {
    tnNavPage('/pages/login/login')
    return
  }
  tnNavPage(
    `/circlesPostPages/report?circlesPostId=${state.circlesPostId}&publishUserId${state.currentCirclesPost.user_id}`
  )
  state.operatePopup = false
}
const setStickyPeriod = () => {
  state.showStickyPeriodPopup = true
}
const clickStickyPeriodDate = () => {
  state.openDateTimePicker = true
}
// 设置置顶
const confirmStickyPeriod = () => {
  console.log('confirmStickyPeriod', state.stickyPeriodDate)
  circles
    .topupDynamic({
      circles_id: state.currentCirclesPost.circles_id,
      circles_post_id: state.circlesPostId,
      top_time: state.stickyPeriodDate,
    })
    .then((res) => {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
      if (res.code == 1) {
        state.showStickyPeriodPopup = false
        state.operatePopup = false
      }
    })
    .catch((err) => {
      console.log(err, 'confirmStickyPeriod')
    })
}
const clickLike = () => {
  circlesPost
    .circlesPostLike({
      circles_post_id: state.circlesPostId,
    })
    .then((res) => {
      if (res.code == 1) {
        if (state.currentCirclesPost.user_is_like == 0) {
          state.currentCirclesPost.user_is_like = 1
          state.currentCirclesPost.like_total += 1
        } else {
          state.currentCirclesPost.user_is_like = 0
          state.currentCirclesPost.like_total -= 1
        }
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        })
      }
    })
    .catch((err) => {
      console.log(err, 'circlesPostLike')
    })
}
// 帖子下架
const circlesPostDelist = () => {
  circlesPost
    .circlesPostDelist({
      circles_post_id: state.circlesPostId,
    })
    .then((res) => {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
      if (res.code == 1) {
        state.operatePopup = false
      }
    })
    .catch((err) => {
      console.log(err, 'circlesPostDelist')
    })
}

// 帖子删除
const circlesPostDelete = () => {
  circlesPost
    .circlesPostDelete({
      circles_post_id: state.circlesPostId,
      circles_id: state.currentCirclesPost.circles_id,
    })
    .then((res) => {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
      if (res.code == 1) {
        state.operatePopup = false
      }
    })
    .catch((err) => {
      console.log(err, 'circlesPostDelete')
    })
}

// 查看更多评论
const showMoreClickHandle = ({ id }: TnShowMoreCommentParams) => {
  // 通过id去请求该评论的回复列表
  const subCommentList = state.commentList.find((items) => items.id === id)
  commentListRef.value?.addCommentData(id, subCommentList.comment)
}
// 回复评论
const replyClickHandle = ({ id, nickname }: TnReplyCommentParams) => {
  state.commentPopup = true
  nextTick(() => {
    state.textareaFocus = true
  })

  state.replyContent = ''
  state.replyNickname = nickname
  state.replyCommentId = Number.parseInt(id)
}
const deleteClickHandle = (id: string | number) => {
  // 通过id从数据库中删除评论
  commentListRef.value?.deleteCommentReply(id)
}
const replyCommentClickHandle = () => {
  if (!state.replyContent) {
    uni.showToast({
      icon: 'none',
      title: '请输入内容',
    })
    return
  }
  state.loading = true
  circlesPost
    .circlesPostComment({
      circles_post_id: state.circlesPostId,
      content: state.replyContent,
      pid: state.replyCommentId,
      channel: uni.getStorageSync(CHANNEL),
    })
    .then((res) => {
      if (res.code == 1) {
        uni.showToast({
          title: '发表成功！',
          icon: 'none',
        })
        state.loading = false

        commentListRef.value?.addCommentReply(state.replyCommentId, {
          id: res.data.id,
          avatar: FILE_URL + state.userInfo.avatar,
          nickname: state.userInfo.nickname,
          date: '2秒前',
          position: res.data.position,
          content: state.replyContent,
          allowDelete: true,
          disabledReply: false,
        })
        state.replyContent = ''
        state.commentPopup = false

        updateUserLevel()
      }
    })
    .catch((err) => {
      console.log(err, 'circlesPostComment')
    })
}
const updateUserLevel = () => {
  user
    .updateUserLevel({
      type: 'comment',
    })
    .then((res) => {})
}
onLoad((options) => {
  if (!options?.circlesPostId) {
    uni.showModal({
      title: '提示',
      content: '参数错误',
      showCancel: false,
      success: () => {
        uni.navigateBack()
      },
    })
    return
  }
  state.circlesPostId = options.circlesPostId
  const userInfo = uni.getStorageSync(USER_INFO)
  if (userInfo) {
    state.userInfo = userInfo
  }
  state.userToken = uni.getStorageSync(USER_TOKEN)
  getCirclesPostDetailComments()
})

onShareAppMessage(() => {
  return {
    title: state.currentCirclesPost.content.slice(0, 30),
    path: `/circlesPostPages/video?circlesPostId=${state.circlesPostId}`,
    imageUrl: '',
  }
})
onShareTimeline(() => {
  return {
    title: state.currentCirclesPost.content.slice(0, 30),
    path: `/circlesPostPages/video?circlesPostId=${state.circlesPostId}`,
    imageUrl: '',
  }
})
</script>

<template>
  <PageContainer :placeholder-bottom="true">
    <TnNavbar
      fixed
      :bottom-shadow="false"
      :placeholder="false"
      @init-finish="navbarInitFinishHandle"
    />
    <z-paging
      ref="paging"
      v-model="state.videoLists"
      :paging-style="{ paddingTop: `${navbarHeight}px` }"
      @query="queryList"
    >
      <view class="">
        <swiper
          class="card-swiper"
          :circular="true"
          vertical="true"
          :autoplay="false"
          duration="500"
          interval="5000"
          @change="cardSwiper"
        >
          <swiper-item
            v-for="(item, index) in state.videoLists"
            :key="index"
            :class="state.cardCur == index ? 'cur' : ''"
          >
            <view class="swiper-item image-banner">
              <video
                v-if="item.id == state.circlesPostId"
                :id="`video-${item.id}`"
                :src="FILE_URL + item.attachment"
                :enable-progress-gesture="false"
                :show-center-play-btn="false"
                :show-loading="false"
                :show-play-btn="false"
                :show-fullscreen-btn="false"
                :controls="false"
                :autoplay="true"
                :enable-play-gesture="true"
                loop
                style="height: 90vh; width: 100%"
              />

              <video
                v-else
                :id="`video-${item.id}`"
                :src="FILE_URL + item.attachment"
                :enable-progress-gesture="false"
                :show-center-play-btn="false"
                :show-loading="false"
                :show-play-btn="false"
                :show-fullscreen-btn="false"
                :controls="false"
                :autoplay="false"
                :enable-play-gesture="true"
                loop
                style="height: 90vh; width: 100%"
              />
            </view>
            <view class="swiper-item-icon image-banner">
              <view class="">
                <view
                  class="user-pic button-0"
                  @click="navUserHomePage(item.user.id)"
                >
                  <view class="user-image">
                    <view
                      class="tn-shadow-blur"
                      :style="
                        'background-image:url(' +
                        FILE_URL +
                        item.user.avatar +
                        ');width: 90rpx;height: 90rpx;background-size: cover;overflow: hidden;'
                      "
                    />
                  </view>
                </view>
                <view
                  class="icon15__item--icon tn-flex tn-flex-column justify-center items-center tn-shadow-blur button-1"
                  @click="clickLike"
                >
                  <view class="">
                    <TnIcon
                      v-if="item.user_is_like == 1"
                      name="like-fill"
                      color="#ff444f"
                      size="80rpx"
                    />
                    <TnIcon v-else name="like-fill" size="80rpx" />
                  </view>
                  <view style="font-size: 20rpx; position: relative">{{
                    item.like_total
                  }}</view>
                </view>
                <view
                  class="icon15__item--icon tn-flex tn-flex-column justify-center items-center tn-shadow-blur button-2"
                  @click="showCommentPopup(item.id)"
                >
                  <view class="">
                    <TnIcon name="message-fill" size="70rpx" />
                  </view>
                  <view style="font-size: 20rpx; position: relative">
                    {{ item.comment_total }}
                  </view>
                </view>
                <view
                  class="icon15__item--icon tn-flex tn-flex-column justify-center items-center tn-shadow-blur button-3"
                  style="height: 100rpx"
                  @click="showOperatePopup(item)"
                >
                  <view class="">
                    <TnIcon name="send-fill" size="70rpx" />
                  </view>
                </view>
              </view>

              <view class="swiper-item-text">
                <view class="tn-flex tn-pr" style="align-items: center">
                  <view
                    class="justify-content-item items-center justify-center tn-text-xl"
                  >
                    <text class="tn-text-bold tn-color-friend">
                      @ {{ item.user.nickname }}
                    </text>
                  </view>
                  <view class="justify-content-item tn-ml-xs">
                    <image
                      v-if="item.user.grade_icon != ''"
                      :src="FILE_URL + item.user.grade_icon"
                      style="width: 60rpx; height: 30rpx; margin-left: 10rpx"
                    />
                  </view>
                </view>
                <view
                  class="tn-pt-sm tn-text-lg tn-text-ellipsis-2"
                  style="width: 85%"
                  @click="clickContent(item.content, item.update_date)"
                >
                  <text>{{ item.content }}</text>
                </view>
              </view>
            </view>
          </swiper-item>
        </swiper>
        <TnPopup
          v-model="state.commentListPopup"
          open-direction="bottom"
          close-btn
          height="800"
          radius="30"
        >
          <view class="tn-p tn-text-center tn-text-bold tn-text-xl">
            评论
          </view>
          <view v-if="state.commentList.length == 0" class="tn-mt-xl">
            <TnEmpty mode="comment" color="#ebebeb" size="xl" />
          </view>
          <view v-else class="comment-list">
            <TnCommentList
              ref="commentListRef"
              :data="state.commentList"
              :show-like="false"
              :show-dislike="false"
              @show-more="showMoreClickHandle"
              @reply="replyClickHandle"
              @delete="deleteClickHandle"
            />
          </view>
          <view class="bottom-operation-bar tn-shadow">
            <view class="search-box tn-radius">
              <TnSearchBox
                :border="false"
                :search-button="false"
                disabled
                placeholder-icon="reply"
                placeholder="言语如春风，温暖友情长"
                @click="clickCommentInput"
              />
            </view>
          </view>
        </TnPopup>
        <TnPopup
          v-model="state.commentPopup"
          width="90%"
          height="260"
          radius="30"
        >
          <view class="popup-box">
            <view
              class="header tn-flex tn-flex-row tn-flex-nowrap justify-between"
            >
              <TnButton
                shape="round"
                bg-color="tn-grey-light"
                text-color="tn-gray"
                @click="closeCommentPopup"
              >
                取消
              </TnButton>
              <view class="tn-text-bold tn-text-lg">评论</view>
              <TnButton
                shape="round"
                :loading="state.loading"
                @click="replyCommentClickHandle"
              >
                发布
              </TnButton>
            </view>
            <view class="content">
              <TnInput
                v-model="state.replyContent"
                type="textarea"
                :placeholder="`回复${state.replyNickname}:`"
                :maxlength="150"
                clearable
                show-word-limit
                height="100"
                :show-confirm-bar="false"
                :cursor-spacing="50"
                :focus="state.textareaFocus"
              />
            </view>
          </view>
        </TnPopup>
        <TnPopup
          v-model="state.contentPopup"
          open-direction="bottom"
          close-btn
          height="500"
        >
          <view class="tn-pt-xl tn-pl tn-pr">
            <view>
              <text>{{ state.content }}</text>
            </view>
            <view class="tn-pt-sm" style="color: #78909c">
              {{ state.updateDate }}
            </view>
          </view>
        </TnPopup>
        <!-- 帖子操作 -->
        <TnPopup v-model="state.operatePopup" open-direction="bottom">
          <view class="tn-p" style="background-color: #f8f7f8">
            <view class="">
              <view class="tn-mb tn-text-center">分享</view>
              <TnScrollList :indicator="false">
                <view class="operate-item-container">
                  <view class="scroll-item">
                    <TnButton
                      only-button
                      open-type="share"
                      @click="shareWechat"
                    >
                      <view class="icon">
                        <TnIcon name="wechat-fill" size="60" color="#00d886" />
                      </view>
                    </TnButton>
                    <view class="title">微信好友</view>
                  </view>
                  <view class="scroll-item" @click="generateMpUrlLink">
                    <view class="icon">
                      <TnIcon name="link" size="50" color="#01beff" />
                    </view>
                    <view class="title">复制链接</view>
                  </view>
                </view>
              </TnScrollList>
            </view>
            <view class="tn-mt-lg">
              <TnScrollList :indicator="false">
                <view class="operate-item-container">
                  <view class="scroll-item" @click="jumpCirclesPostReport">
                    <view class="icon">
                      <TnIcon name="warning" size="50" />
                    </view>
                    <view class="title">投诉举报</view>
                  </view>
                  <view
                    v-if="state.currentCirclesPost.circles_manage == 1"
                    class="scroll-item"
                    @click="setStickyPeriod"
                  >
                    <view class="icon">
                      <TnIcon name="bookmark" size="50" />
                    </view>
                    <view class="title">置顶</view>
                  </view>
                  <view
                    v-if="
                      state.currentCirclesPost.circles_manage == 1 ||
                      state.currentCirclesPost.user_id == state.userInfo.id
                    "
                    class="scroll-item"
                    @click="circlesPostDelist"
                  >
                    <view class="icon">
                      <TnIcon name="clear" size="50" />
                    </view>
                    <view class="title">下架</view>
                  </view>
                  <view
                    v-if="state.currentCirclesPost.user_id == state.userInfo.id"
                    class="scroll-item"
                    @click="circlesPostDelete"
                  >
                    <view class="icon">
                      <TnIcon name="delete" size="50" />
                    </view>
                    <view class="title">删除</view>
                  </view>
                </view>
              </TnScrollList>
            </view>
          </view>
        </TnPopup>

        <!-- 置顶期限 -->
        <TnPopup v-model="state.showStickyPeriodPopup" width="80%" height="330">
          <view class="tn-p-lg">
            <view class="tn-text-center tn-text-bold">请设置置顶期限</view>
            <view class="tn-mt tn-mb">
              <TnInput
                v-model="state.stickyPeriodDate"
                type="select"
                placeholder="请选择置顶期限"
                :custom-style="{
                  backgroundColor: 'transparent',
                }"
                @click="clickStickyPeriodDate"
              />
            </view>
            <view class="tn-mt-lg tn-text-center">
              <TnButton
                width="100%"
                height="70rpx"
                @click="confirmStickyPeriod"
              >
                确 认
              </TnButton>
            </view>
          </view>
        </TnPopup>
        <!-- 选择日期与时间 -->
        <TnDateTimePicker
          v-model="state.stickyPeriodDate"
          v-model:open="state.openDateTimePicker"
          min-time="2025-01-01"
          mode="date"
          format="YYYY-MM-DD"
        />
      </view>
    </z-paging>
  </PageContainer>
</template>
<style lang="scss" scoped>
@use './styles/video.scss';
.operate-item-container {
  position: relative;
  width: fit-content;
  margin-bottom: 15rpx;
  display: flex;
  flex-wrap: nowrap;

  .scroll-item {
    margin-right: 40rpx;
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #f8f7f8;

    .icon {
      background-color: var(--tn-color-white);
      width: 90rpx;
      height: 90rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 15%;
    }

    .title {
      margin-top: 15rpx;
      font-size: 22rpx;
      color: var(--tn-color-gray-dark);
    }
  }
}
</style>
